package com.zzzzzz.topic.service;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.zzzzzz.account.model.User;
import com.zzzzzz.common.util.Constants;
import com.zzzzzz.common.util.FileUtils;
import com.zzzzzz.core.data.filestore.FileData;
import com.zzzzzz.core.data.filestore.FileStorage;
import com.zzzzzz.core.exception.NoSuchTopicException;
import com.zzzzzz.topic.dao.TopicDao;
import com.zzzzzz.topic.model.AddTopicForm;
import com.zzzzzz.topic.model.Category;
import com.zzzzzz.topic.model.Topic;

@Service("topicService")
public class TopicServiceImpl implements TopicService {

	@Resource 
	private TopicDao topicDao;

	@Resource 
	CategoryService categoryService;
	
	@Resource
	private FileStorage fileStorage;
	
	
	public void add(AddTopicForm addTopicForm, User user) throws IOException {
		Topic topic = new Topic();
		addTopicForm.getPo(topic);
		topic.setUser(user);
		
		Category category = categoryService.findByLb(addTopicForm.getCategory());
		topic.setCategoryId(category.getId());
		
		Date now = new Date();
		topic.setAddDt(now);
		
		CommonsMultipartFile files = addTopicForm.getFiles();
		if(files != null) {
			// actual image
			FileData imgData = FileUtils.getResizedImageData(files, Constants.IMAGE.TOPIC_MAX_WIDTH, Constants.IMAGE.TOPIC_MAX_HEIGHT, false);
			String imgId = fileStorage.storeFile(imgData);
			topic.setImgId(imgId);
			// thumbnail
			FileData imgSData = FileUtils.getResizedImageData(files, Constants.IMAGE.TOPIC_THUMBNAIL_MAX_WIDTH, Constants.IMAGE.TOPIC_THUMBNAIL_MAX_HEIGHT, false);
			String imgSId = fileStorage.storeFile(imgSData);
			topic.setImgSId(imgSId);
		}
		
		topic.setStatus(0);
		
		
		topicDao.add(topic);
	}

	public void edit(Topic topic) {
		topicDao.edit(topic);
	}
	
	public void editStatus(String topicId, Integer status) {
		topicDao.editStatus(topicId, status);
	}

	public Topic findById(String topicId) throws NoSuchTopicException {
		return topicDao.findById(topicId);
	}
	
	public List<Topic> findByCategoryLb(String categoryLb, int start, int offset, boolean ascending) {
		String categoryId = categoryService.findByLb(categoryLb).getId();
		return findByCategoryId(categoryId, start, offset, ascending);
	}
	
	public List<Topic> findByCategoryId(String categoryId, int start, int offset, boolean ascending) {
		return topicDao.findByCategoryId(categoryId, start, offset, ascending);
	}
	
	public long findByCategoryIdCount(String categoryId) {
		return topicDao.findByCategoryIdCount(categoryId);
	}
	
}
